/*
 * Copyright (C) 2007-2008  Hylke van der Schaaf
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3 of the License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package hextd.message;

import hextd.message.MessageFactory.NetworkMessage;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MessageTowerSell implements GameMessage {

	public NetworkMessage type = NetworkMessage.TowerSell;
	public static String RegExp = "S ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)";
	//int gameTime, int sender, int row, int col
	public static Pattern MessagePattern = Pattern.compile(MessageTowerSell.RegExp);
	//
	private String message;
	private int tick;
	private int senderId = -2;
	private int row;
	private int col;

	public static String formatMessage(Integer playerId, int tick, int row, int col) {
		String message = "S " + tick + " " + playerId.toString() + " " + row + " " + col;
		return message;
	}

	public MessageTowerSell() {
	}

	private MessageTowerSell(String message) {
		this.message = message;
		Matcher matcher = MessageTowerSell.MessagePattern.matcher(message);
		if (matcher.matches()) {
			try {
				this.tick = new Integer(matcher.group(1)).intValue();
				this.senderId = new Integer(matcher.group(2)).intValue();
				this.row = new Integer(matcher.group(3)).intValue();
				this.col = new Integer(matcher.group(4)).intValue();
			} catch (NumberFormatException e) {
				System.err.println("MessageTowerSell: invalid id in: " + matcher.group(1));
			}
		}
	}

	@Override
	public int getTick() {
		return this.tick;
	}

	@Override
	public String getMessage() {
		return this.message;
	}

	@Override
	public Message initFromString(String message) {
		return new MessageTowerSell(message);
	}

	@Override
	public int getSenderId() {
		return this.senderId;
	}

	@Override
	public void setSenderId(int id) {
		this.senderId = id;
		this.message = MessageTowerSell.formatMessage(senderId, tick, row, col);
	}

	@Override
	public Pattern getPattern() {
		return MessageTowerSell.MessagePattern;
	}

	@Override
	public NetworkMessage getType() {
		return this.type;
	}

	public int getRow() {
		return row;
	}

	public int getCol() {
		return col;
	}
}
